<template>
  <div>
    <div class="search">
      <el-input placeholder="请输入商品名称查询" style="width: 200px" v-model="name"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="operation">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
    </div>


      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all" ></el-tab-pane>
        <el-tab-pane label="待处理" name="awaitingApproval" ></el-tab-pane>
        <el-tab-pane label="完成纠纷" name="disapproved" ></el-tab-pane>
        <el-tab-pane label="驳回纠纷" name="onShelf"></el-tab-pane>
      </el-tabs>


    <div class="table">
      <el-table :data="tableData" strip @selection-change="handleSelectionChange">
        <el-table-column prop="id" label="序号" width="70" align="center" sortable></el-table-column>
        <el-table-column label="证明图片" width="100">
          <template v-slot="scope">
            <div>
              <el-image
                  style="width: 60px; height: 60px; border-radius: 4px;"
                  :src="parseImageUrls(scope.row.imageUrls)[0] || defaultImageUrl"
                  :preview-src-list="parseImageUrls(scope.row.imageUrls)">
              </el-image>
              <el-button type="text" @click="previewAllImages(parseImageUrls(scope.row.imageUrls))" v-if="parseImageUrls(scope.row.imageUrls).length > 1">
                查看所有图片
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="number" label="单号"></el-table-column>
        <el-table-column prop="orderNumber" label="所属单号"></el-table-column>
        <el-table-column prop="remarks" label="售后内容"></el-table-column>
        <el-table-column prop="userId" label="用户ID"></el-table-column>
        <el-table-column prop="type" label="反馈类型"></el-table-column>
        <el-table-column prop="status" label="状态"></el-table-column>
        <el-table-column prop="processingTime" label="处理时间"></el-table-column>
        <el-table-column prop="processingEmployee" label="审核员工"></el-table-column>
        <el-table-column prop="processingData" label="处理完成备注"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="createUser" label="创建人"></el-table-column>
        <el-table-column label="操作" align="center" width="145" v-if="activeTab === 'awaitingApproval'">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)" >处理</el-button>
<!--            <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>


      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>


    <template>
      <el-dialog title="售后" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close @close="handleCancel">
        <el-form :model="form" label-width="100px" style="padding-right: 50px" ref="formRef">
          <el-descriptions border class="margin-bottom-20" :column="Number('1')">
            <el-descriptions-item label="单号">{{ form.number }}</el-descriptions-item>
            <el-descriptions-item label="所属订单">{{ form.orderNumber }}</el-descriptions-item>
            <el-descriptions-item label="异常卡密">
              <div :style="{ whiteSpace: 'pre-wrap', minWidth: '400px' }">
                <ul>
                  <li v-for="(item, index) in form.cdKey.split(',')" :key="index">{{ index + 1 }}. {{ item }}</li>
                </ul>
              </div>
            </el-descriptions-item>

          </el-descriptions>

          <el-descriptions border class="margin-bottom-20" :column="Number('3')">
            <el-descriptions-item label="用户" span="1">{{ form.userId }}</el-descriptions-item>
            <el-descriptions-item label="反馈类型" span="1">
              <span v-if="form.type === 1">退货</span>
              <span v-else-if="form.type === 2">退款</span>
              <span v-else>未知类型</span>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" span="1">{{ form.createTime }}</el-descriptions-item>
          </el-descriptions>

          <el-descriptions border class="margin-bottom-20">
            <el-descriptions-item label="用户提供内容">
              <div :style="{ minWidth: '400px' }">{{ form.remarks }}</div>
            </el-descriptions-item>
          </el-descriptions>

          <el-form-item label="备注" prop="processingData" style="margin-top: 20px; margin-left: -25px;">
            <el-input
                type="textarea"
                v-model="form.processingData"
                placeholder="备注"
                maxlength="255"
                show-word-limit
                autosize
            ></el-input>
          </el-form-item>

          <el-form-item label="证明图片" prop="name">
            <div style="display: flex; flex-wrap: wrap;">
              <el-image
                  v-for="(url, index) in previewImages"
                  :key="index"
                  style="width: 100px; height: 100px; margin-right: 10px; margin-bottom: 10px;"
                  :src="url"
                  :preview-src-list="previewImages">
              </el-image>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <el-button @click="passAudit(1)" v-if="activeTab === 'awaitingApproval'">通 过</el-button>
          <el-button @click="passAudit(2)" v-if="activeTab === 'awaitingApproval'">驳 回</el-button>
        </div>
      </el-dialog>
    </template>

    <el-dialog title="查看图片" :visible.sync="imageDialogVisible" width="50%">
      <div style="display: flex; flex-wrap: wrap;">
        <el-image
            v-for="(url, index) in previewImages"
            :key="index"
            style="width: 100px; height: 100px; margin-right: 10px; margin-bottom: 10px;"
            :src="url"
            :preview-src-list="previewImages">
        </el-image>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="imageDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Product",
  data() {
    return {
      //默认图片
      defaultImageUrl: 'https://img0.baidu.com/it/u=2991630058,871933297&fm=253&fmt=auto&app=138&f=JPEG?w=300&h=300',
      //默认预览
      defaultPreviewUrl: 'https://img0.baidu.com/it/u=2594677340,3536341249&fm=253&fmt=auto&app=138&f=JPG?w=240&h=240',
      tableData: [],  // 所有的数据
      imageDialogVisible: false, // 控制图片预览对话框的显示
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      currentState: null, // 添加一个变量来存储当前选中的状态
      activeTab: 'all',
      productsData: [], // 商品数据
      specificationsData: [], // 所有规格数据
      filteredSpecifications: [], // 过滤后的规格数据
      fileList: [], //详细图片
      previewImages: [], // 预览的所有图片
      minDate: new Date(), // 当前日期
      isAuditMode: false, // 是否是审核模式
      isShelfMode: false, // 是否是上架模式
      total: 0,
      name: null,
      state:null,
      fromVisible: false,
      form: {
        cdKey: '', // 初始化 cdKey 属性
      },
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      ids: []
    }
  },
  created() {
    this.activeTab = 'all'; // 设置默认激活的标签页为 '全部'
    this.load(1); // 调用 load 方法加载全部数据
    this.loadProducts();//获取商品信息
    this.loadSpcifications();//获取商品规格信息

  },
  methods: {
    previewAllImages(urls) {
      if (urls && urls.length > 0) {
        this.previewImages = urls;
        this.imageDialogVisible = true;
      }
    },
    parseImageUrls(jsonString) {
      try {
        const urls = JSON.parse(jsonString);
        if (Array.isArray(urls)) {
          return urls;
        }
        return [];
      } catch (error) {
        console.error("Error parsing image URLs:", error);
        return [];
      }
    },
    passAudit(status) {
      console.log(status);
      // 设置状态
      this.form.status = status;
      if (this.user.admin === undefined) {
        this.form.processingEmployee = this.user.employee.id;
      } else {
        this.form.processingEmployee = this.user.admin.id;
      }

      // 在保存之前，先检查是否有替换商品
      this.$request.get(`/employee/api/safter/Sales`).then(res => {
        if (res.code === 0) {
          // 如果存在替换商品，显示提示框
          this.$confirm('存在替换商品，您确定要处理吗？', '确认处理', {
            type: 'warning'
          }).then(() => {
            // 用户确认处理，调用保存方法
            this.save();
          }).catch(() => {
            // 用户取消处理
            this.$message.info('已取消处理');
          });
        } else {
          // 如果不存在替换商品，显示提示框询问是否进行退款操作
          this.$confirm('没有替换商品，您是否要进行退款操作？', '确认退款', {
            type: 'warning'
          }).then(() => {
            // 用户确认退款，调用退款方法
            this.save();
          }).catch(() => {
            // 用户取消退款
            this.$message.info('已取消处理');
          });
        }
      }).catch(error => {
        console.error('检查替换商品失败:', error);
        this.$message.error('检查替换商品失败');
      });
    },

    disablePastDate(time) {
      const date = new Date();
      date.setDate(date.getDate() + 7); // 当前日期加7天
      return time < date;
    },
    loadProducts() { //获取商品数据
      if (this.user.admin === undefined){
        this.$request.get('/employee/api/product/pages').then(res => {
          this.productsData = res.records;
          console.log( this.productsData)
          this.productsData = this.uniqueProducts(this.productsData);
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }else{
        this.$request.get('/admin/api/product/pages').then(res => {
          this.productsData = res.records;
          console.log( this.productsData)
          this.productsData = this.uniqueProducts(this.productsData);
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }

    },
    uniqueProducts(products) { //去重方法
      const uniqueProducts = new Map();
      products.forEach((product) => {
        if (!uniqueProducts.has(product.id)) {
          uniqueProducts.set(product.id, product);
        }
      });
      return Array.from(uniqueProducts.values());
    },
    loadSpcifications() { //获取商品数据
      if (this.user.admin === undefined){
        this.$request.get('/employee/api/specifications/pages').then(res => {
          this.specificationsData = res.records;
          console.log(this.specificationsData)
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }else {
        this.$request.get('/admin/api/specifications/pages').then(res => {
          this.specificationsData = res.records;
          console.log(this.specificationsData)
        }).catch(error => {
          console.error('获取商品数据失败:', error);
        });
      }

    },
    handleProductChange(productId) {
      this.filteredSpecifications = this.specificationsData.filter(spec => spec.productId === productId);
      // 遍历数组来找到匹配的规格并设置价格
      this.filteredSpecifications.forEach((spec) => {
        if (spec.id === this.form.specificationsId) {
          this.form.price = spec.price;
          return; // 找到匹配的规格后可以停止遍历
        }
      });
    },
    formatState(row, column, cellValue) {
      // 根据state的值返回相应的文本
      switch(cellValue) {
        case 0:
          return '待处理';
        case 1:
          return '完成纠纷';
        case 2:
          return '驳回纠纷';
        default:
          return '未知状态';
      }
    },
    handleAdd() {   // 新增数据
      this.form = {
        state: '0', //状态默认为未上架
      }
      this.isAuditMode = false; // 设置为编辑模式
      this.fromVisible = true   // 打开弹窗
    },
    handleCancel(){
      this.fileList = [];
      this.form.imageUrls = [];
      this.fromVisible = false
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝数据
      // 确保触发商品规格变化的方法来更新价格
      this.handleProductChange(this.form.productId);
      this.isAuditMode = true; // 设置为审核模式
      this.fromVisible = true; // 打开弹窗

      // 在编辑模式下加载图片
      this.previewImages = this.parseImageUrls(this.form.imageUrls);
    },

    handleOffShelf(row) {   // 设置上架
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝数据
      // 确保触发商品规格变化的方法来更新价格
      this.handleProductChange(this.form.productId);
      this.isAuditMode = true; // 设置为审核模式
      this.isShelfMode = false; // 设置为上架模式
      this.fromVisible = true; // 打开弹窗
    },
    handleOnShelf(row) {   // 设置下架
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝数据
      // 确保触发商品规格变化的方法来更新价格
      this.handleProductChange(this.form.productId);
      this.isAuditMode = true; // 设置为审核模式
      this.isShelfMode = true; // 设置为上架模式
      this.fromVisible = true; // 打开弹窗
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (this.user.admin === undefined){
          if (valid) {
            this.$request({
              url: this.form.id ? '/employee/api/safter/update' : '/employee/api/safter/add',
              method: this.form.id ? 'PUT' : 'POST',
              data: this.form
            }).then(res => {
              if (res.code === 0) {  // 表示成功保存
                this.$message.success('保存成功')
                this.load(1)
                this.fromVisible = false
              } else {
                this.$message.error(res.msg)  // 弹出错误的信息
                console.log(res)
              }
            })
          }
        }else {
          if (valid) {
            this.$request({
              url: this.form.id ? '/admin/api/safter/update' : '/admin/api/safter/add',
              method: this.form.id ? 'PUT' : 'POST',
              data: this.form
            }).then(res => {
              if (res.code === 0) {  // 表示成功保存
                this.$message.success('保存成功')
                this.load(1)
                this.fromVisible = false
              } else {
                this.$message.error(res.msg)  // 弹出错误的信息
                console.log(res)
              }
            })
          }
        }

      })
    },
    del(id) {   // 单个删除
      if (this.user.admin === undefined){

      }else {

      }
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/admin/api/safter/delete/' + id).then(res => {
          if (res.code === 0) {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },


    handleTabClick(tab) {
      console.log('handleTabClick 方法被调用了');
      switch(tab.name) {
        case 'awaitingApproval':
          this.currentState = 0; // 待处理
          break;
        case 'disapproved':
          this.currentState = 1; // 完成纠纷处理
          break;
        case 'onShelf':
          this.currentState = 2; // 驳回纠纷
          break;
        case 'all':
          this.currentState = null; // 全部
          break;
        default:
          this.currentState = null;
      }

      this.load(1); // 重新加载表格数据
    },
    load(pageNum) {
      if (pageNum) this.pageNum = pageNum;
      let requestUrl = this.user.admin === undefined ? '/employee/api/safter/pages' : '/admin/api/safter/pages';
      this.$request.get(requestUrl, {
        params: {
          current: this.pageNum,
          size: this.pageSize,
          // 添加状态参数，如果currentState为null，则不传递该参数，即查询所有状态
          status: this.currentState !== null ? this.currentState : undefined,
        }
      }).then(res => {
        this.tableData = res.records;
        this.total = res.total;
      })
    },

    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把头像属性换成上传的图片的链接
      this.form.imageUrl = response.data
    },
    reset() {
      this.name = null
      this.load(1)
    },
  }
}

</script>

<style scoped>

</style>